<script setup>
import { adminStorage } from '@/utils/storage'
import { h } from "vue";
import { ElNotification } from 'element-plus'
class UpdateVer {
  constructor(options) {
    this.options = options || {}
    this.dispatch = {}
    this.init()
    this.timer = null
    this.opt = {
      duration: 3000,
      title: '版本更新',
      message: h('h4', { style: 'color: teal' }, '请刷新页面获取最新版本！'),
      type: 'info',
      onClose: function () {
        alert('请刷新页面后关闭提示')
        ElNotification(this.opt)
      }
    }
  }
  async init() {
    clearInterval(this.timer)
    let re = await this.getHtml()
    let value = JSON.parse(re).version
    adminStorage.setSession(value, 'update_version')
    this.timing(this.options?.timer)
  }
  async getHtml() {
    const html = await fetch(`/update_version.json`, {
      headers: {
        'Cache-control': 'no-cache, no-store, must-revalidate',
        'Pragma': 'no-cache',
        'Expires': 0
      },
    }).then(res => res.text());//读取index html

    return html
  }
  on(key = 'no-update' | 'update', fn) {
    (this.dispatch[key] || (this.dispatch[key] = [])).push(fn)
    return this;
  }

  timing(time = 10000) {
    //轮询
    this.timer = setInterval(async () => {
      const newHtml = await this.getHtml()
      let newValue = JSON.parse(newHtml).version
      let OleVale = adminStorage.getSession('update_version')
      if (newValue === OleVale) {
        //未更新
        this.dispatch['no-update'].forEach(fn => {
          fn()
        })
      } else {
        //更新
        this.dispatch['update'].forEach(fn => {
          fn()
        })
      }
    }, time)
  }
}
let uv = new UpdateVer({ timer: 10000 })
//未更新通知
uv.on('no-update', () => {
  console.log('未更新')
})
//更新通知
uv.on('update', () => {
  console.log('更新了')
  ElNotification({
    ...uv.opt,
    onClose: function () {
      alert('请刷新页面后关闭提示!')
      ElNotification(uv.opt)
    }
  })
})
// ElNotification({
//     ...uv.opt,
//     onClose: function () {
//       alert('请刷新页面后关闭提示2222222222222')
//       ElNotification(uv.opt)
//     }
//   })

</script>
